from PyQt5.QtCore import QTimer, Qt
from PyQt5.QtGui import QPaintEvent, QColor
from PyQt5.QtWidgets import QFrame, QHBoxLayout, QLabel, QGraphicsDropShadowEffect


class MessageBox(QFrame):
    def __init__(self, parent=None):
        super(MessageBox, self).__init__(parent)
        self._pixmap = None
        self._text = None

        self.setFixedHeight(50)
        self.setMinimumSize(100, 50)
        self.setWindowFlags(Qt.WindowStaysOnTopHint)

        self.hBox = QHBoxLayout(self)
        self.imgLabel = QLabel()
        self.textLabel = QLabel()
        self.textLabel.setTextInteractionFlags(Qt.TextSelectableByMouse)

        self.setObjectName("MessageBox")
        self.imgLabel.setObjectName("imgLabel")
        self.textLabel.setObjectName("textLabel")

        self.hBox.addWidget(self.imgLabel)
        self.hBox.addWidget(self.textLabel)

        if self.parent():
            x = (self.parent().width() - self.width()) // 2
            self.move(x, 40)

        self.timer = QTimer(self)
        self.timer.timeout.connect(self.close)
        self.timer.setSingleShot(True)
        self.timer.start(2000)

        self._setQss()
        self.setShadowEffect()
        self.show()

    def _setQss(self):
        qss = '''
        QFrame#MessageBox {
            background-color: rgba(0, 0, 0, 0.65);
            border-radius: 20px;
        }
        QLabel#textLabel {
            background-color: transparent;
            color: white;
            font: 13pt 'Segoe UI', 'Microsoft YaHei', 'PingFang SC';
        }
        '''
        self.setStyleSheet(qss)

    def setText(self, text):
        self.textLabel.setText(text)
        self.textLabel.adjustSize()
        self.adjustSize()
        if self.parent():
            x = (self.parent().width() - self.width()) // 2
            self.move(x, 40)
        self.update()

    def text(self):
        return self.textLabel.text()

    def setPixmap(self, pixmap):
        self.imgLabel.setPixmap(pixmap)

    def pixmap(self):
        return self.imgLabel.pixmap()

    def paintEvent(self, a0: QPaintEvent) -> None:
        super().paintEvent(a0)
        if self.pixmap() is None:
            self.imgLabel.hide()
            self.textLabel.setAlignment(Qt.AlignCenter)
        else:
            self.imgLabel.show()
            self.textLabel.setAlignment(Qt.AlignLeft)

    def setShadowEffect(self, blurRadius=10, offset=(0, 0), color=QColor(0, 0, 0, 100)):
        """ add shadow to dialog """
        shadowEffect = QGraphicsDropShadowEffect(self)
        shadowEffect.setBlurRadius(blurRadius)
        shadowEffect.setOffset(*offset)
        shadowEffect.setColor(color)
        self.setGraphicsEffect(None)
        self.setGraphicsEffect(shadowEffect)

    @classmethod
    def info(cls, parent, text: str):
        msg = MessageBox(parent)
        msg.setText(text)
